package com.wht.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wht.domain.DtsRole;
import com.wht.mapper.DtsRoleMapper;
import com.wht.service.DtsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author wanghaotian
 * time:2022/12/01,0001 22:16
 * description:
 */

@Service
public class DtsRoleServiceImpl implements DtsRoleService {

    @Autowired
    private DtsRoleMapper roleMapper;

    @Override
    public Set<String> queryByIds(Integer[] roleIds) {
        Set<String> roles = new HashSet<>();
        if(roleIds == null || roleIds.length == 0){
            return roles;
        }

        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        wrapper.in("id", Arrays.asList(roleIds));
        wrapper.eq("deleted",false);
        wrapper.eq("enabled", true);
        List<DtsRole> list = roleMapper.selectList(wrapper);
        for (DtsRole role : list) {
            roles.add(role.getName());
        }
        return roles;
    }

    @Override
    public IPage<DtsRole> querySelective(String name, Integer page, Integer limit, String sort, String order) {
        IPage<DtsRole> iPage = new Page<>();
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        wrapper.eq("deleted", false);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            if(order.equalsIgnoreCase("desc")){
                wrapper.orderByDesc(sort);
            }else {
                wrapper.orderByAsc(sort);
            }
        }
        iPage = roleMapper.selectPage(iPage, wrapper);
        return iPage;
    }

    @Override
    public List<DtsRole> queryAll() {
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        return roleMapper.selectList(wrapper);
    }

    @Override
    public DtsRole findById(Integer id) {
        return roleMapper.selectById(id);
    }

    @Override
    public boolean chechExist(String name) {
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        wrapper.eq("name", name);
        Integer count = roleMapper.selectCount(wrapper);
        return count != 0;
    }

    @Override
    public void add(DtsRole role) {
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        roleMapper.insert(role);
    }

    @Override
    public void updateById(DtsRole role) {
        role.setUpdateTime(new Date());
        roleMapper.updateById(role);
    }
}
